package com.zeyi.chat.handler;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.annotation.Mapping;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.manager.SocketManager;
import com.zeyi.chat.po.User;
import com.zeyi.chat.service.UserService;
import com.zeyi.chat.utils.EmailUtil;
import com.zeyi.chat.utils.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;

import java.net.Socket;
import java.util.Map;

/**
 * @author zeyi
 */
public class UserHandler {

    private UserHandler() {
    }

    private static class Singleton {
        public static final UserHandler INSTANCE = new UserHandler();
    }

    public static UserHandler getInstance() {
        return UserHandler.Singleton.INSTANCE;
    }

    /**
     * 处理登录
     */
    @Mapping("login")
    public Message handleLogin(Message message, Dispatcher dispatcher) {
        User user = JSON.parseObject(message.getData(), User.class);
        User queryUser = UserService.getInstance().login(user, dispatcher);
        if (queryUser != null) {
            if(SocketManager.getSocket(queryUser.getId()) != null) {
                return new Message(false, message.getHandlePath(), "不能重复登录");
            }
            SocketManager.addSocket(queryUser.getId(), dispatcher.getSocket());
            return new Message(true, message.getHandlePath(), JSON.toJSONString(queryUser));
        } else {
            return new Message(false, message.getHandlePath(), "用户名或密码错误");
        }
    }

    /**
     * 处理注册
     */
    @Mapping("register")
    public Message handleRegister(Message message) {
        Map<String, String> map = JSON.parseObject(message.getData(), Map.class);
        String checkCode = map.get("checkCode");
        String email = map.get("email");
        String key = "checkCode" + email;
        String code = RedisUtil.get(key);
        if (code == null) return new Message(false, message.getHandlePath(), "验证码过期");
        if (!checkCode.equals(code)) return new Message(false, message.getHandlePath(), "验证码错误");
        RedisUtil.del(key);
        String username = map.get("username");
        String password = map.get("password");
        String avatar = map.get("avatar");
        User user = new User(email, username, DigestUtils.md5Hex(password), avatar);
        User registerUser = UserService.getInstance().register(user);
        if (registerUser != null) {
            return new Message(true, message.getHandlePath(), JSON.toJSONString(user));
        } else {
            return new Message(false, message.getHandlePath(), "邮箱已注册");
        }
    }

    /**
     * 处理发送邮箱验证码
     */
    @Mapping("email")
    public Message handleEmail(Message message, Socket socket) {
        String email = message.getData();
        User user = UserService.getInstance().findByEmail(email);
        if (user != null) {
            return new Message(false, message.getHandlePath(), "邮箱已注册");
        }
        //生成随机数
        String checkCode = RandomStringUtils.randomNumeric(6);
        RedisUtil.save("checkCode" + email, checkCode, 60000 * 5);
        TaskHandler.submit(() -> {
            if (EmailUtil.sendEmail(email, checkCode)) {
                SocketManager.send(socket, new Message(true, message.getHandlePath(), "已发送验证码到邮箱"));
            } else {
                SocketManager.send(socket, new Message(false, message.getHandlePath(), "邮箱不存在"));
            }
        });
        return null;
    }
}
